//
//  TextureRender.swift
//  Pods
//
//  Created by vincepzhang on 2024/10/16.
//

import FlutterMacOS
import TXLiteAVSDK_TRTC_Mac
import Accelerate
import Dispatch

class TextureRender: NSObject, FlutterTexture, TRTCVideoRenderDelegate {
        
        
    private let register: FlutterPluginRegistrar
    private let channel: FlutterMethodChannel
    
    private var latestPixelBuffer: CVPixelBuffer?
    
    private let textures: FlutterTextureRegistry
    private var textureId: Int64 = 0
    
    init(register: FlutterPluginRegistrar, channel: FlutterMethodChannel) {
        self.register = register
        self.channel = channel
        textures = register.textures
        super.init()
        textureId = textures.register(self)
    }
    
    func getTextureId() -> Int64 {
        return textureId
    }
    
    func copyPixelBuffer() -> Unmanaged<CVPixelBuffer>? {
        if let buffer = latestPixelBuffer {
            return Unmanaged.passRetained(buffer)
        }
        return nil
    }
    
    public func onRenderVideoFrame( _ frame:TRTCVideoFrame, userId:String?, streamType:TRTCVideoStreamType){
        guard let nv12Buffer = frame.pixelBuffer else { return }
        latestPixelBuffer = nv12Buffer
        textures.textureFrameAvailable(textureId)
    }    
}
